/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 *
 */

import fs from 'fs';
import Module from 'module';
import * as path from 'path';
import os from 'os';
import ts, { TranspileOptions } from 'typescript';

import { formatDiagnostic } from '../../internal/util/ts_check.js';
import { HvigorLogger } from '../../log/hvigor-log.js';
import { compilerOptions } from '../../util/options/compile-options.js';

const log = HvigorLogger.getLogger('require_hook');

const to: TranspileOptions = {
  compilerOptions: compilerOptions,
  reportDiagnostics: true,
};

function extensionHandler(module: any, filename: string) {
  const fileFullPath = path.resolve(__dirname, filename);
  const content = fs.readFileSync(fileFullPath, 'utf-8');
  const res = ts.transpileModule(content, to);
  handleDiagnostics(fileFullPath, res.diagnostics);
  module._compile(res.outputText, filename);
}

function handleDiagnostics(fileName: string, diagnostics: ts.Diagnostic[] | undefined) {
  const formatHost: ts.FormatDiagnosticsHost = {
    getCanonicalFileName: (path) => path,
    getCurrentDirectory: ts.sys.getCurrentDirectory,
    getNewLine: () => ts.sys.newLine,
  };

  diagnostics?.forEach((diagnostic) => {
    log.error(formatDiagnostic(diagnostic, formatHost, fileName));
  });
  diagnostics?.length && log.errorMessageExit('Please fix above syntax errors.');
}

export function addExtensionHandler(suffixes: string[]) {
  for (const suffix of suffixes) {
    (Module as any)._extensions[suffix] = extensionHandler;
  }
}

addExtensionHandler(['.ts', '.mjs']);
